from hqchartpy2_fast import FastHQChart, IHQData
import json
import time
import csv
import pandas as pd
import pymongo
import redis
import time
import os.path
import pymysql
from apscheduler.schedulers.blocking import BlockingScheduler
import Delivier
import threading
import tqdm
from tqdm import tqdm, trange
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import threading
import _thread
from quota_function import F_L_S_G,D_T_P_L,D_K_D_Y_X,J_S_J,D_X_F_Z,Q_S_Z_L,X_R_Z_L
from value_cache.glabalVal import cacheValue
from apscheduler.triggers.interval import IntervalTrigger
from apscheduler.triggers.cron import CronTrigger
from utils.RedisUtil import getRedis
from utils.RedisUtil import getReleaseRedis
# cacheValue.STOCK_LIST = []  # 股票列表
# cacheValue.CAPITAL_LIST = []  # 流通股本列表
# Cache = {}  # 所有股票缓存的数据


class HQChartData(IHQData):
    def __init__(self):
        a = 0
        # self.Cache={}   #缓存

    def GetKLineData(self, symbol, period, right, jobID):
        if (symbol in cacheValue.Cache):
            return cacheValue.Cache[symbol]

        ###---------------------------

        sourceUrl = 'data/day/{0}.csv'.format(symbol);
        Kline_data = pd.read_csv(sourceUrl, nrows=600)  # 读取单只股票数据

        dataCount = Kline_data.shape[0]
        name = symbol  # 暂时先用股票代码代替名字

        cacheData = {}
        cacheData['count'] = dataCount  # 数据个数
        cacheData['name'] = name  # 股票名称

        aryDate = []
        aryClose = []
        aryYClose = []
        aryOpen = []
        aryHigh = []
        aryLow = []
        aryVol = []
        aryAmount = []
        Kline_data = Kline_data.iloc[::-1]
        for index, row in Kline_data.iterrows():
            aryDate.append(row['_id'])
            aryYClose.append(round(row['preClose'], 2))
            aryOpen.append(round(row['open'], 2))
            aryHigh.append(round(row['high'], 2))
            aryLow.append(round(row['low'], 2))
            aryClose.append(round(row['close'], 2))
            aryVol.append(row['vol'] * 100)
            aryAmount.append(row['money'])

        cacheData["date"] = aryDate
        # cacheData["time"]=aryTime
        cacheData["yclose"] = aryYClose
        cacheData["open"] = aryOpen
        cacheData["high"] = aryHigh
        cacheData["low"] = aryLow
        cacheData["close"] = aryClose
        cacheData["vol"] = aryVol
        cacheData["amount"] = aryAmount

        log = "K线:{0} - period={1} right={2} count={3}".format(symbol, period, right, dataCount)
        print(log)

        cacheValue.Cache[symbol] = cacheData
        return cacheData

    def GetFinance(self, symbol, id, period, right, kcount, jobID):
        pyCacheData = []
        for i in range(kcount):  # 生成财务数据
            pyCacheData.append(8976549.994 + i)

        data = {"type": 1, "data": pyCacheData}
        return data

    def GetDynainfo(self, symbol, id, period, right, kcount, jobID):
        data = {"type": 0, "data": 5}
        return data

    def GetCapital(self, symbol, period, right, kcount, jobID):
        data = {"type": 0, "data": 29350000000}
        return data

    # 历史所有的流通股
    def GetHisCapital(self, symbol, period, right, kcount, jobID):
        pyCacheData = []
        for i in range(kcount):  # 生成流通股数据
            if symbol in cacheValue.CAPITAL_LIST[0]:
                pyCacheData.append(cacheValue.CAPITAL_LIST[0][symbol][1])
            else:
                pyCacheData.append(1000000)
        data = {"type": 1, "data": pyCacheData}
        return data

    # 大盘数据
    def GetIndex(self, symbol, varName, period, right, kcount, jobID):
        if (varName == u'INDEXA'):  # 大盘成交额
            pass
        elif (varName == u'INDEXC'):  # 大盘收盘价
            pass
        elif (varName == u'INDEXH'):  # 大盘最高价
            pass
        elif (varName == u'INDEXL'):  # 大盘最低价
            pass
        elif (varName == u'INDEXO'):  # 大盘开盘价
            pass
        elif (varName == u'INDEXV'):  # 大盘成交量
            pass
        elif (varName == u'INDEXADV'):  # 上涨家数
            pass
        elif (varName == u'INDEXDEC'):  # 下跌家数
            pass

        # 测试数据
        pyCacheData = []
        for i in range(kcount):
            pyCacheData.append(2888.8 + i)
        data = {"type": 1, "data": pyCacheData}
        return data

    #


class Mail:
    def __init__(self):
        # 第三方 SMTP 服务

        self.mail_host = "smtp.qq.com"  # 设置服务器:这个是qq邮箱服务器，直接复制就可以
        self.mail_pass = "fjtsopizziuabdhf"  # 刚才我们获取的授权码
        self.sender = '979900170@qq.com'  # 你的邮箱地址
        self.receivers = ['519173829@qq.com', '420347238@qq.com', '2443363137@qq.com',
                          '571941989@qq.com']  # 收件人的邮箱地址，可设置为你的QQ邮箱或者其他邮箱，可多个

    def send(self):

        content = '选股引擎历史日K同步失败'
        message = MIMEText(content, 'plain', 'utf-8')

        message['From'] = Header("King", 'utf-8')
        message['To'] = Header("Kings", 'utf-8')

        subject = '选股引擎历史数据警报'  # 发送的主题，可自由填写
        message['Subject'] = Header(subject, 'utf-8')
        try:
            smtpObj = smtplib.SMTP_SSL(self.mail_host, 465)
            smtpObj.login(self.sender, self.mail_pass)
            smtpObj.sendmail(self.sender, self.receivers, message.as_string())
            smtpObj.quit()
            print('邮件发送成功')
        except smtplib.SMTPException as e:
            print('邮件发送失败')


class HQResultTest():
    def __init__(self):
        self.Result = []  # 保存所有的执行结果
        self.IsOutLog = True  # 是否输出日志
        self.count = 0

    # 执行成功回调
    def RunSuccess(self, symbol, jsData, jobID):
        # self.Result.append({"Symbol":symbol, "Data":jsData})  # 保存结果
        try:
            jsonResult = json.loads(jsData)
            if (jsonResult['OutVar'][0]['Data'][0] is None):
                return
            else:
                if (jsonResult['OutVar'][0]['Data'][0] == 1.0):
                    fun_name = ''
                    if (jobID == '1'):
                        fun_name = '四点共振短线'
                    if (jobID == '2'):
                        fun_name = '一阳穿多线'
                    if (jobID == '3'):
                        fun_name = '长下影线'
                    if (jobID == '4'):
                        fun_name = '四点共振中线'
                    if (jobID == '5'):
                        fun_name = '早晨之星'
                    if (jobID == '6'):
                        fun_name = '多方炮'
                    now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
                    self.Result.append({"Symbol": symbol, "StockName": cacheValue.CAPITAL_LIST[0][symbol][2], "Fnc_type": jobID,
                                        "DateTime": now_time, "Fnc_name": fun_name})  # 保存符合条件的股票结果
                    self.count = self.count + 1

            if (self.IsOutLog):
                log = "{0} success".format(symbol)
                print(log)
                print(jsData)

        except Exception as e:
            print(e)

    # 执行失败回调
    def RunFailed(self, code, symbol, error, jobID):
        # print(symbol)
        log = "{0}\n{1} failed\n{2}".format(code, symbol, error)
        print(log)


# 单股票指标
def TestSingleStock():
    runConfig = {
        # 系统指标名字
        # "Name":"MA",
        "Script": '''
        KF:=(O-REF(C,1))/REF(C,1)*100;
ZF:=(C-REF(C,1))/REF(C,1)*100;
限幅:=KF<3.82 AND KF>-3.82; 
ZT:=C>1.1*REF(C,1)-0.01 AND C<1.1*REF(C,1)+0.01 AND C=H; 
一字:=C>1.1*REF(C,1)-0.01 AND C<1.1*REF(C,1)+0.01 AND H=O AND L=H; 
去一:=NOT(一字);
XG:限幅 AND 去一 AND BARSSINCE(C<>O AND BARSCOUNT(CLOSE)<>1)>30 AND O<>HHV(H,2); 
        ''',
        # 脚本参数
        # "Args":[ { "Name": 'N1', "Value": 5 },{ "Name": 'N2', "Value": 10 },{ "Name": 'N3', "Value": 15 } ],
        "Args": [{"Name": "M1", "Value": 15}, {"Name": "M2", "Value": 20}, {"Name": "M3", "Value": 30}],
        # 周期 复权
        "Period": 0, "Right": 0,
        "Symbol": "600000.sh",

        # jobID (可选)
        "JobID": "1234-555-555"
    }

    jsConfig = json.dumps(runConfig)  # 运行配置项
    hqData = HQChartData()  # 实例化数据类
    result = HQResultTest()  # 实例计算结果接收类
    result.IsOutLog = True

    start = time.process_time()

    res = FastHQChart.Run(jsConfig, hqData, proSuccess=result.RunSuccess, procFailed=result.RunFailed)

    elapsed = (time.process_time() - start)
    log = "TestSingleStock() Time used:{0}, 股票{1}".format(elapsed, runConfig['Symbol'])
    print(log)


# 股票池
def TestMultiStock():
    runConfig = {
        # 系统指标名字
        # "Name":"MA",
        # 执行的脚本
        "Script": '''
        A4:=(HIGH+LOW+3*CLOSE)/5;
        A8:=EMA(A4,3);
        KF:=EMA(A8,5);
        DF:=EMA(KF + (A8 - KF) * 5,3);
        MA5:=MA(CLOSE,5);
        MA10:=MA(CLOSE,10);
        五日均线在十日之上:=MA5>MA10;
        A22:=(HIGH+LOW+CLOSE)/3;
        A33:=SUM(MAX(0,HIGH - REF(A22,1)),26) / SUM(MAX(0,REF(A22,1) - LOW),26) * 100;
        A44:=EMA(A33,4);
        VA:=IF(CLOSE>REF(CLOSE,1),VOL,0-VOL);
        OBV:=SUM(IF(CLOSE=REF(CLOSE,1),0,VA),0);
        A88:=OBV;
        MMNL:=A44 * A88;
        QS:=EMA(SLOPE(MMNL,21) * 20 + MMNL,55);
        量能符合:=MMNL>QS;
        获利盘:=MA(WINNER(CLOSE),3) * 100 ;
        牛熊符合:=获利盘 > 50;
        XG:CROSS(DF,KF)  AND 量能符合 ;
        ''',
        # 脚本参数
        # "Args":[ { "Name": 'N1', "Value": 5 },{ "Name": 'N2', "Value": 10 },{ "Name": 'N3', "Value": 15 } ],
        "Args": [{"Name": "M1", "Value": 15}, {"Name": "M2", "Value": 20}, {"Name": "M3", "Value": 30}],
        # 周期 复权
        "Period": 0, "Right": 0,
        # 股票池
        "Symbol": [],
        # 并行计算加速模式
        "Mode": {"Thread": False, "MinRunCount": 1000, "Count": 5},
        # 输出数据个数 如果只需要最后几个数据可以填几个的个数, 数据从最后开始返回的, 如1=返回最后1个数据 2=返回最后2个数组,  -1=返回所有的数据
        "OutCount": 1,
        # 单个股票执行完是否立即清空缓存, 更具K线个数配置, 不清空缓存到占用很多内存
        "ClearCache": True

        # 获利盘:MA(WINNER(CLOSE),3) * 100 ;
    }

    # 批量执行的股票
    # for i in range(3700) :
    #     # runConfig["Symbol"].append("600000.sh")
    #     runConfig["Symbol"].append("000421.sz")
    # 加载股票列表到配置中
    for i in cacheValue.STOCK_LIST:
        runConfig["Symbol"].append(i)
    # for i in cacheValue.STOCK_LIST:
    #     runConfig["Symbol"].append('600000.sh')
    sourceUrl = 'data\mfinancial_data\mfinancial.csv';
    Cap_Df = pd.read_csv(sourceUrl)
    mDict = Cap_Df.set_index('ths_thscode_stock').T.to_dict('list')
    cacheValue.CAPITAL_LIST.append(mDict)
    jsConfig = json.dumps(runConfig)  # 运行配置项
    hqData = HQChartData()  # 实例化数据类
    result = HQResultTest()  # 实例计算结果接收类
    result.IsOutLog = False

    # 预加载K线数据
    # start = time.process_time()
    # loadCount=0
    # loadCount=HQChart.PreLoadKData(runConfig,data,guid=strGuid)
    # elapsed = (time.process_time() - start)
    # log="加载数据 Time used:{0}, 股票个数:{1}".format(elapsed, loadCount)
    # print(log)

    start = time.process_time()
    res = FastHQChart.Run(jsConfig, hqData, proSuccess=result.RunSuccess, procFailed=result.RunFailed)
    elapsed = (time.process_time() - start)
    log = "执行指标 Time used:{0}, 股票个数:{1}".format(elapsed, len(runConfig['Symbol']))
    print(log)
    for key in str:
        print(key['Symbol'])


def getRedis():
    # redisObkect = redis.StrictRedis(host='192.168.0.164', port=6379, db=0, password='Mysqlycjr0715#', decode_responses=True)
    redisObkect = redis.StrictRedis(host='192.168.0.164', port=6379, db=0, password='123456', decode_responses=True)
    return redisObkect

def getReleaseRedis():
    redisObkect = redis.StrictRedis(host='39.105.51.148', port=6379, db=0, password='Mysqlycjr0715#',
                                    decode_responses=True)
    return redisObkect
def getMongodb():
    myclient = pymongo.MongoClient("mongodb://192.168.0.164:27017/")  # mongo连接
    return myclient


# 读取所有股票历史记录
def readSingleStockKlineHistory():
    ##获取redis中股票代码列表开始
    redisObkect = getRedis()
    # myclient = pymongo.MongoClient("mongodb://192.168.0.164:27017/")#mongo连接 dev
    myclient = pymongo.MongoClient("mongodb://192.168.0.164:27017/")  # mongo连接 王建虚拟机
    mydb = myclient.STOCK_DAY_DATA
    mydb.authenticate("qq", "123456", "admin")
    nameset = redisObkect.hgetall('Stock_Base_Message')
    keys = nameset.keys()
    print('股票总数' + str(len(keys)))
    pbar = tqdm(keys)
    # stockHisMonitor(mydb)
    for i in pbar:  # 生成流通股数据
        mycol = mydb[i]
        resultCursor = mycol.find().sort("_id", pymongo.DESCENDING).limit(600)
        # time.sleep(200)
        data = list(resultCursor)
        df = pd.DataFrame(data)
        df.to_csv('data/day/' + i + '.csv')

    print('历史数据同步成功...')
    ##结束

    #
    # mydb = myclient.STOCK_DAY_DATA
    # mycol = mydb["000001.sz"]
    #
    #
    # resultCursor = mycol.find().sort("dateTime", pymongo.DESCENDING).limit(500)
    #
    # for a in resultCursor:
    #     print(a)
    #
    # dataCount = resultCursor.count(with_limit_and_skip=True)  # 数据个数
    # cacheData = {}
    # cacheData['count'] = resultCursor.count(with_limit_and_skip=True)  # 数据个数
    # cacheData['name'] = "平安银行"  # 股票名称
    #
    # aryDate = []
    # aryClose = []
    # aryYClose = []
    # aryOpen = []
    # aryHigh = []
    # aryLow = []
    # aryVol = []
    # aryAmount = []


# 进行异常处理流程,检测是否有见天的日K
def stockHisMonitor(mydb):
    mMonitor = mydb['000001.sz']
    resultCursor = mMonitor.find().sort("_id", pymongo.DESCENDING).limit(600)
    mdata = list(resultCursor)
    mHistoryTemp = mdata[0]
    stockHisTime = mHistoryTemp['dateTime']
    now = datetime.now()  # 当前时间
    strnow = datetime.strftime(now, '%Y%m%d')
    if (stockHisTime != strnow):
        mail = Mail()
        mail.send()
    else:
        print('历史数据日期验证通过')


# 缓存股票列表信息并保存在本地csv文件
def cacheStoctList():
    redisObkect = getRedis()
    nameset = redisObkect.hgetall('Stock_Base_Message')
    keys = nameset.keys()
    data = list(keys)
    df = pd.DataFrame(data)
    df.to_csv('codeList\stockList.csv')
    print('股票列表文件同步完成')


# 读取股票列表并且缓存在全局变量
def readStockList():
    sourceUrl = 'codeList\stockList.csv';
    stock_codes = pd.read_csv(sourceUrl, names=['number', 'code'])  # 读取单只股票数据
    for index, row in stock_codes.iterrows():
        if (row['code'] == '600519.sh' or row['code'] == '688169.sh' or row['code'] == '300896.sz'):  # 后两个没有数据数据完整后需要去掉
            continue
        else:
            if (os.path.isfile('data/day/' + row['code'] + '.csv')):
                cacheValue.STOCK_LIST.append(row['code'])

    # or row['code'] == '603707.sh'or row['code'] == '002977.sz'


def synFinance():
    if (os.path.isfile('data\mfinancial_data\mfinancial.csv')):
        print('财务数据文件已经存在是否覆盖更新:0;更新 1:不更新')
        InPut = input("input:")
    if (InPut == '0'):
        try:
            conn = pymysql.connect(host='192.168.0.152', \
                                   user='root', password='root', \
                                   db='cg152', charset='utf8', \
                                   use_unicode=True)
            sql = 'select ths_thscode_stock,ths_total_float_shares_stock,ths_stock_short_name_stock from stock_basic'
            df = pd.read_sql(sql, con=conn)
            df.to_csv('data\mfinancial_data\mfinancial.csv')
            conn.close()
            print('财务数据同步成功')
        except:
            print('同步财务数据失败')

    if (InPut == '1'):
        try:
            conn = pymysql.connect(host='192.168.0.152', \
                                   user='root', password='root', \
                                   db='cg152', charset='utf8', \
                                   use_unicode=True)
            sql = 'select ths_thscode_stock,ths_total_float_shares_stock,ths_stock_short_name_stock from stock_basic'
            df = pd.read_sql(sql, con=conn)
            df.to_csv('data\mfinancial_data\mfinancial.csv')
            conn.close()
            print('财务数据同步成功')
        except:
            print('同步财务数据失败')
        # print(cacheValue.CAPITAL_LIST)


def mutiThredLoadHistoryKline(*args):
    for key in args[1]:
        print(key)


def LoadHisLineMemoryQuick():
    stockListDict = Delivier.bisector_list(cacheValue.STOCK_LIST, 40)
    mCount = 0;
    for listKey in stockListDict:
        t = threading.Thread(target=mutiThredLoadHistoryKline, name='LoopThread', args=(1, listKey), )
        t.start()
        # for key in listKey:
        #     mCount = mCount +1
    print(mCount)
    # if (len(Cache) == 0):
    #     print('开始缓存历史数据...')
    #     for symbol in cacheValue.STOCK_LIST:
    #         sourceUrl = 'data/day/{0}.csv'.format(symbol);
    #         Kline_data = pd.read_csv(sourceUrl, nrows=800)  # 读取单只股票数据
    #         dataCount = Kline_data.shape[0]
    #         name = symbol  # 暂时先用股票代码代替名
    #         cacheData = {}
    #         cacheData['count'] = dataCount  # 数据个数
    #         cacheData['name'] = name  # 股票名称
    #         aryDate = []
    #         aryClose = []
    #         aryYClose = []
    #         aryOpen = []
    #         aryHigh = []
    #         aryLow = []
    #         aryVol = []
    #         aryAmount = []
    #         Kline_data = Kline_data.iloc[::-1]
    #         for index, row in Kline_data.iterrows():
    #             aryDate.append(row['_id'])
    #             aryYClose.append(round(row['preClose'], 2))
    #             aryOpen.append(round(row['open'], 2))
    #             aryHigh.append(round(row['high'], 2))
    #             aryLow.append(round(row['low'], 2))
    #             aryClose.append(round(row['close'], 2))
    #             aryVol.append(row['vol'] * 100)
    #             aryAmount.append(row['money'])
    #
    #         cacheData["date"] = aryDate
    #         # cacheData["time"]=aryTime
    #         cacheData["yclose"] = aryYClose
    #         cacheData["open"] = aryOpen
    #         cacheData["high"] = aryHigh
    #         cacheData["low"] = aryLow
    #         cacheData["close"] = aryClose
    #         cacheData["vol"] = aryVol
    #         cacheData["amount"] = aryAmount
    #         Cache[symbol] = cacheData
    #     print('缓存历史数据完毕...')


def LoadHisLineMemory():
    if (len(cacheValue.Cache) == 0):
        print('开始缓存历史数据...')
        pbar = tqdm(cacheValue.STOCK_LIST)
        for symbol in pbar:
            sourceUrl = 'data/day/{0}.csv'.format(symbol);
            # _thread.start_new_thread(CachHistoryData, (symbol, symbol, ))
            Kline_data = pd.read_csv(sourceUrl, nrows=600)  # 读取单只股票数据
            dataCount = Kline_data.shape[0]
            name = symbol  # 暂时先用股票代码代替名
            cacheData = {}
            cacheData['count'] = dataCount  # 数据个数
            cacheData['name'] = name  # 股票名称
            aryDate = []
            aryClose = []
            aryYClose = []
            aryOpen = []
            aryHigh = []
            aryLow = []
            aryVol = []
            aryAmount = []
            Kline_data = Kline_data.iloc[::-1]
            for index, row in Kline_data.iterrows():
                aryDate.append(row['_id'])
                aryYClose.append(round(row['preClose'], 2))
                aryOpen.append(round(row['open'], 2))
                aryHigh.append(round(row['high'], 2))
                aryLow.append(round(row['low'], 2))
                aryClose.append(round(row['close'], 2))
                aryVol.append(row['vol'] * 100)
                aryAmount.append(row['money'])

            cacheData["date"] = aryDate
            # cacheData["time"]=aryTime
            cacheData["yclose"] = aryYClose
            cacheData["open"] = aryOpen
            cacheData["high"] = aryHigh
            cacheData["low"] = aryLow
            cacheData["close"] = aryClose
            cacheData["vol"] = aryVol
            cacheData["amount"] = aryAmount
            cacheValue.Cache[symbol] = cacheData
        print('缓存历史数据完毕...')

# 缓存历史数据线程
def CachHistoryData(threadName,symbol):
    sourceUrl = 'data/day/{0}.csv'.format(symbol);
    Kline_data = pd.read_csv(sourceUrl, nrows=600)  # 读取单只股票数据
    dataCount = Kline_data.shape[0]
    name = symbol  # 暂时先用股票代码代替名
    cacheData = {}
    cacheData['count'] = dataCount  # 数据个数
    cacheData['name'] = name  # 股票名称
    aryDate = []
    aryClose = []
    aryYClose = []
    aryOpen = []
    aryHigh = []
    aryLow = []
    aryVol = []
    aryAmount = []
    Kline_data = Kline_data.iloc[::-1]
    for index, row in Kline_data.iterrows():
        aryDate.append(row['_id'])
        aryYClose.append(round(row['preClose'], 2))
        aryOpen.append(round(row['open'], 2))
        aryHigh.append(round(row['high'], 2))
        aryLow.append(round(row['low'], 2))
        aryClose.append(round(row['close'], 2))
        aryVol.append(row['vol'] * 100)
        aryAmount.append(row['money'])

    cacheData["date"] = aryDate
    # cacheData["time"]=aryTime
    cacheData["yclose"] = aryYClose
    cacheData["open"] = aryOpen
    cacheData["high"] = aryHigh
    cacheData["low"] = aryLow
    cacheData["close"] = aryClose
    cacheData["vol"] = aryVol
    cacheData["amount"] = aryAmount
    cacheValue.Cache[symbol] = cacheData
    pass

# 四点共振中线选股
def sdgz_zx():
    runConfig = {
        # 系统指标名字
        # "Name":"MA",
        # 执行的脚本
        "Script": '''
            MID:=(3*CLOSE+LOW+OPEN+HIGH)/6;
            晨光短线:=(20*MID+19*REF(MID,1)+18*REF(MID,2)+17*REF(MID,3)+16*REF(MID,4)+
            15*REF(MID,5)+14*REF(MID,6)+13*REF(MID,7)+12*REF(MID,8)+11*REF(MID,9)+
            10*REF(MID,10)+9*REF(MID,11)+8*REF(MID,12)+7*REF(MID,13)+6*REF(MID,14)+
            5*REF(MID,15)+4*REF(MID,16)+3*REF(MID,17)+2*REF(MID,18)+REF(MID,20))/210;
            短线趋势:=MA(晨光短线,7);
            MA5:=MA(CLOSE,5);
            MA10:=MA(CLOSE,10);
            五日均线在十日之上:=MA5>MA10;
            A22:=(HIGH+LOW+CLOSE)/3;
            A33:=SUM(MAX(0,HIGH - REF(A22,1)),26) / SUM(MAX(0,REF(A22,1) - LOW),26) * 100;
            A44:=EMA(A33,4);
            VA:=IF(CLOSE>REF(CLOSE,1),VOL,0-VOL);
            OBV:=SUM(IF(CLOSE=REF(CLOSE,1),0,VA),0);
            A88:=OBV;
            MMNL:=A44 * A88;
            QS:=EMA(SLOPE(MMNL,21) * 20 + MMNL,55);
            量能符合:=MMNL>QS;
            获利盘:=MA(WINNER(CLOSE),3) * 100 ;
            牛熊符合:=获利盘 > 49;
            XG:CROSS(晨光短线,短线趋势) AND 量能符合 AND 牛熊符合;
            ''',
        # 脚本参数
        # "Args":[ { "Name": 'N1', "Value": 5 },{ "Name": 'N2', "Value": 10 },{ "Name": 'N3', "Value": 15 } ],
        "Args": [{"Name": "M1", "Value": 15}, {"Name": "M2", "Value": 20}, {"Name": "M3", "Value": 30}],
        # 周期 复权
        "Period": 0, "Right": 0,
        # 股票池
        "Symbol": [],
        # 并行计算加速模式
        "Mode": {"Thread": False, "MinRunCount": 1000, "Count": 5},
        # 输出数据个数 如果只需要最后几个数据可以填几个的个数, 数据从最后开始返回的, 如1=返回最后1个数据 2=返回最后2个数组,  -1=返回所有的数据
        "OutCount": 1,
        # 单个股票执行完是否立即清空缓存, 更具K线个数配置, 不清空缓存到占用很多内存
        "ClearCache": True,

        "JobID": "4"
        # 获利盘:MA(WINNER(CLOSE),3) * 100 ;
    }

    # 加载股票列表到配置中
    for i in cacheValue.STOCK_LIST:
        runConfig["Symbol"].append(i)
    # for i in cacheValue.STOCK_LIST:
    #     runConfig["Symbol"].append('600000.sh')
    sourceUrl = 'data\mfinancial_data\mfinancial.csv';
    Cap_Df = pd.read_csv(sourceUrl)
    mDict = Cap_Df.set_index('ths_thscode_stock').T.to_dict('list')
    cacheValue.CAPITAL_LIST.append(mDict)
    jsConfig = json.dumps(runConfig)  # 运行配置项
    hqData = HQChartData()  # 实例化数据类
    result = HQResultTest()  # 实例计算结果接收类
    result.IsOutLog = False

    start = time.process_time()
    res = FastHQChart.Run(jsConfig, hqData, proSuccess=result.RunSuccess, procFailed=result.RunFailed)
    elapsed = (time.process_time() - start)
    log = "执行四点共振中线指标 Time used:{0}, 股票个数:{1}".format(elapsed, len(runConfig['Symbol']))
    print(log)
    for stockResult in result.Result:
        print(stockResult['Symbol'])

    # 选股结果存入redis
    warringResultToRedis(4, result.Result)
    # r = redis.StrictRedis(host='192.168.0.164', port=6379, db=0, password='')
    # r.hset("FNC_WARRING","sdgz_zx", result.Result)  # 将内容写入redis
    # # 选股结果存入mysql
    # con = pymysql.connect('192.168.0.152', 'root', 'root')
    # cur = con.cursor()
    # cur.execute('use cg152')
    # now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    # for stockResult in result.Result:
    #     print(stockResult['Symbol'])
    #     cur.execute("insert into fnc_warning values('%s','%s','%s','%s','%s')" % (
    #     stockResult['Symbol'], stockResult['StockName'], '四点共振短线', 1, now_time))
    # cur.execute('select * from fnc_warning')
    # a = cur.fetchall()
    # con.commit()
    # con.close()


# 四点共振短线选股
def sdgz_dx():
    runConfig = {
        # 系统指标名字
        # "Name":"MA",
        # 执行的脚本
        "Script": '''
            A4:=(HIGH+LOW+3*CLOSE)/5;
            A8:=EMA(A4,3);
            KF:=EMA(A8,5);
            DF:=EMA(KF + (A8 - KF) * 5,3);
            MA5:=MA(CLOSE,5);
            MA10:=MA(CLOSE,10);
            五日均线在十日之上:=MA5>MA10;
            A22:=(HIGH+LOW+CLOSE)/3;
            A33:=SUM(MAX(0,HIGH - REF(A22,1)),26) / SUM(MAX(0,REF(A22,1) - LOW),26) * 100;
            A44:=EMA(A33,4);
            VA:=IF(CLOSE>REF(CLOSE,1),VOL,0-VOL);
            OBV:=SUM(IF(CLOSE=REF(CLOSE,1),0,VA),0);
            A88:=OBV;
            MMNL:=A44 * A88;
            QS:=EMA(SLOPE(MMNL,21) * 20 + MMNL,55);
            量能符合:=MMNL>QS;
            获利盘:=MA(WINNER(CLOSE),3) * 100 ;
            牛熊符合:=获利盘 > 49;
            空方上穿多方:=CROSS(DF,KF) 
            XG:CROSS(DF,KF) AND 量能符合 AND 牛熊符合;
            ''',
        # 脚本参数
        # "Args":[ { "Name": 'N1', "Value": 5 },{ "Name": 'N2', "Value": 10 },{ "Name": 'N3', "Value": 15 } ],
        "Args": [{"Name": "M1", "Value": 15}, {"Name": "M2", "Value": 20}, {"Name": "M3", "Value": 30}],
        # 周期 复权
        "Period": 0, "Right": 0,
        # 股票池
        "Symbol": [],
        # 并行计算加速模式
        "Mode": {"Thread": False, "MinRunCount": 1000, "Count": 5},
        # 输出数据个数 如果只需要最后几个数据可以填几个的个数, 数据从最后开始返回的, 如1=返回最后1个数据 2=返回最后2个数组,  -1=返回所有的数据
        "OutCount": 1,
        # 单个股票执行完是否立即清空缓存, 更具K线个数配置, 不清空缓存到占用很多内存
        "ClearCache": True,

        "JobID": "1"
        # 获利盘:MA(WINNER(CLOSE),3) * 100 ;
    }

    # 加载股票列表到配置中
    for i in cacheValue.STOCK_LIST:
        runConfig["Symbol"].append(i)
    # for i in cacheValue.STOCK_LIST:
    #     runConfig["Symbol"].append('600000.sh')
    sourceUrl = 'data\mfinancial_data\mfinancial.csv';
    Cap_Df = pd.read_csv(sourceUrl)
    mDict = Cap_Df.set_index('ths_thscode_stock').T.to_dict('list')
    cacheValue.CAPITAL_LIST.append(mDict)
    jsConfig = json.dumps(runConfig)  # 运行配置项
    hqData = HQChartData()  # 实例化数据类
    result = HQResultTest()  # 实例计算结果接收类
    result.IsOutLog = False

    start = time.process_time()
    res = FastHQChart.Run(jsConfig, hqData, proSuccess=result.RunSuccess, procFailed=result.RunFailed)
    elapsed = (time.process_time() - start)
    log = "执行四点共振短线指标 Time used:{0}, 股票个数:{1}".format(elapsed, len(runConfig['Symbol']))
    print(log)
    for stockResult in result.Result:
        print(stockResult['Symbol'])

    # 选股结果存入redis
    warringResultToRedis(1, result.Result)

    # # 选股结果存入mysql
    # con = pymysql.connect('192.168.0.152', 'root', 'root')
    # cur = con.cursor()
    # cur.execute('use cg152')
    # now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    # for stockResult in result.Result:
    #     print(stockResult['Symbol'])
    #     cur.execute("insert into fnc_warning values('%s','%s','%s','%s','%s')" % (
    #     stockResult['Symbol'], stockResult['StockName'], '四点共振短线', 1, now_time))
    # cur.execute('select * from fnc_warning')
    # a = cur.fetchall()
    # con.commit()
    # con.close()


def UPdateRealTimeData():
    try:
        # redisObkect = getRedis()  #测试环境
        redisObkect = getRedis()  #正式环境
        nameset = redisObkect.hgetall('Real_time_Stock_Data')
        keys = nameset.keys()
        for stockCode in cacheValue.STOCK_LIST:
            stockDataTemp = cacheValue.Cache[stockCode]
            cacheSize = len(stockDataTemp['date'])
            #如果数据少下一只
            if(cacheSize <=1):
                continue
            stockDataRealTime = stockDataTemp['date'][cacheSize - 1]
            today_time = time.strftime('%Y%m%d ', time.localtime(time.time()))  # 当日时间
            if (stockCode in nameset.keys()):
                jsonResult = json.loads(nameset[stockCode])  # 实时数据json格式
                # 判断是否有今天的数据 有就更新 没有就添加数据
                if (stockDataRealTime == int(today_time)):
                    stockDataTemp['yclose'][cacheSize - 1] = jsonResult['preClose']
                    stockDataTemp['open'][cacheSize - 1] = (jsonResult['open'])  # 开盘
                    stockDataTemp['high'][cacheSize - 1] = (jsonResult['high'])
                    stockDataTemp['low'][cacheSize - 1] = (jsonResult['low'])
                    stockDataTemp['close'][cacheSize - 1] = (jsonResult['newPrice'])  # 实时价格
                    stockDataTemp['vol'][cacheSize - 1] = (jsonResult['vol'])
                    stockDataTemp['amount'][cacheSize - 1] = (jsonResult['money'])
                else:
                    stockDataTemp['date'].append(int(jsonResult['dateTime'][0:8]))  # 时间
                    stockDataTemp['yclose'].append(jsonResult['preClose'])  # 昨收
                    stockDataTemp['open'].append(jsonResult['open'])  # 开盘
                    stockDataTemp['high'].append(jsonResult['high'])
                    stockDataTemp['low'].append(jsonResult['low'])
                    stockDataTemp['close'].append(jsonResult['newPrice'])  # 实时价格
                    stockDataTemp['vol'].append(jsonResult['vol'])
                    stockDataTemp['amount'].append(jsonResult['money'])
                    cacheValue.Cache[stockCode]['count'] = cacheValue.Cache[stockCode]['count'] + 1
            else:
                print(stockCode + '实时行情数据异常')
        print('实时数据更新成功开始选股...')
    except Exception as e:
        print('实时数据更新失败...')
        sendWarningMessage(e)
        print(e)


# 一阳穿多线选股
def yycdx():
    runConfig = {
        # 系统指标名字
        # "Name":"MA",
        # 执行的脚本
        "Script": '''
            A1:=C/OPEN>0.05;
            A2:=CROSS(C,MA(C,30));
            A3:=CROSS(C,MA(C,60));
            A4:=CROSS(C,MA(C,120));
            XG:A1 AND A2 AND A3 AND A4 ;
            ''',
        # 脚本参数
        # "Args":[ { "Name": 'N1', "Value": 5 },{ "Name": 'N2', "Value": 10 },{ "Name": 'N3', "Value": 15 } ],
        "Args": [{"Name": "M1", "Value": 15}, {"Name": "M2", "Value": 20}, {"Name": "M3", "Value": 30}],
        # 周期 复权
        "Period": 0, "Right": 0,
        # 股票池
        "Symbol": [],
        # 并行计算加速模式
        "Mode": {"Thread": False, "MinRunCount": 1000, "Count": 5},
        # 输出数据个数 如果只需要最后几个数据可以填几个的个数, 数据从最后开始返回的, 如1=返回最后1个数据 2=返回最后2个数组,  -1=返回所有的数据
        "OutCount": 1,
        # 单个股票执行完是否立即清空缓存, 更具K线个数配置, 不清空缓存到占用很多内存
        "ClearCache": True,

        "JobID": "2"
        # 获利盘:MA(WINNER(CLOSE),3) * 100 ;
    }

    # 加载股票列表到配置中
    for i in cacheValue.STOCK_LIST:
        runConfig["Symbol"].append(i)

    sourceUrl = 'data\mfinancial_data\mfinancial.csv';
    Cap_Df = pd.read_csv(sourceUrl)
    mDict = Cap_Df.set_index('ths_thscode_stock').T.to_dict('list')
    cacheValue.CAPITAL_LIST.append(mDict)

    jsConfig = json.dumps(runConfig)  # 运行配置项
    hqData = HQChartData()  # 实例化数据类
    result = HQResultTest()  # 实例计算结果接收类
    result.IsOutLog = False

    start = time.process_time()
    res = FastHQChart.Run(jsConfig, hqData, proSuccess=result.RunSuccess, procFailed=result.RunFailed)
    elapsed = (time.process_time() - start)
    log = "一阳穿多线 Time used:{0}, 股票个数:{1}".format(elapsed, len(runConfig['Symbol']))
    print(log)

    warringResultToRedis(2, result.Result)
    # r = redis.StrictRedis(host='192.168.0.164', port=6379, db=0, password='')
    # r.hset("FNC_WARRING","yycdx", result.Result)  # 将内容写入redis
    # # 选股结果存入mysql
    # con = pymysql.connect('192.168.0.152', 'root', 'root')
    # cur = con.cursor()
    # cur.execute('use cg152')
    # now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    # for stockResult in result.Result:
    #     print(stockResult['Symbol'])
    #     cur.execute("insert into fnc_warning values('%s','%s','%s','%s','%s')" % (
    #     stockResult['Symbol'], stockResult['StockName'], '一阳穿多线', 2, now_time))
    # cur.execute('select * from fnc_warning')
    # a = cur.fetchall()
    # con.commit()
    # con.close()


def getReleaseRedis():
    redisObkect = redis.StrictRedis(host='39.105.51.148', port=6379, db=0, password='Mysqlycjr0715#',
                                    decode_responses=True)

    # redisObkect = redis.StrictRedis(host='192.168.0.164', port=6379, db=0, password='123456', decode_responses=True)
    return redisObkect


def warringResultToRedis(type, result):
    r = getReleaseRedis()
    rDebug = getRedis()

    # 四点共振短线
    if (type == 1):
        mResult = {'FncName': "四点共振短线", 'Data': result, 'Fnc_type': 1}
        r.hset("FNC_WARRING", "sdgz_dx", mResult)  # 将内容写入redis
        rDebug.hset("FNC_WARRING", "sdgz_dx", mResult)  # 将内容写入redis

        pass
    # 一阳穿多线
    if (type == 2):
        mResult = {'FncName': "一阳穿多线", 'Data': result, 'Fnc_type': 2}
        r.hset("FNC_WARRING", "yycdx", mResult)  # 将内容写入redis
        rDebug.hset("FNC_WARRING", "yycdx", mResult)  # 将内容写入redis
        pass
    # 长下影线
    if (type == 3):
        mResult = {'FncName': "长下影线", 'Data': result, 'Fnc_type': 3}
        r.hset("FNC_WARRING", "cxyx", mResult)  # 将内容写入redis
        rDebug.hset("FNC_WARRING", "cxyx", mResult)  # 将内容写入redis
        pass
    # 四点共振中线
    if (type == 4):
        mResult = {'FncName': "四点共振中线", 'Data': result, 'Fnc_type': 4}
        r.hset("FNC_WARRING", "sdgz_zx", mResult)  # 将内容写入redis
        rDebug.hset("FNC_WARRING", "sdgz_zx", mResult)  # 将内容写入redis
        pass
    # 早晨之星
    if (type == 5):
        mResult = {'FncName': "早晨之星", 'Data': result, 'Fnc_type': 5}
        r.hset("FNC_WARRING", "zczx", mResult)  # 将内容写入redis
        rDebug.hset("FNC_WARRING", "zczx", mResult)  # 将内容写入redis
        pass
    # 多方炮
    if (type == 6):
        mResult = {'FncName': "多方炮", 'Data': result, 'Fnc_type': 6}
        r.hset("FNC_WARRING", "dfp", mResult)  # 将内容写入redis
        rDebug.hset("FNC_WARRING", "dfp", mResult)  # 将内容写入redis
        pass


def TestUp():
    try:
        for stockCode in cacheValue.STOCK_LIST:
            stockDataTemp = cacheValue.Cache[stockCode]
            cacheSize = len(stockDataTemp['date'])
            stockDataRealTime = stockDataTemp['date'][cacheSize - 1]
            today_time = time.strftime('%Y%m%d ', time.localtime(time.time()))  # 当日时间
            # 判断是否有今天的数据 有就更新 没有就添加数据

            stockDataTemp['date'].append(20201224)  # 时间
            stockDataTemp['yclose'].append(8.5)  # 昨收
            stockDataTemp['open'].append(8.44)  # 开盘
            stockDataTemp['high'].append(9.35)
            stockDataTemp['low'].append(8.33)
            stockDataTemp['close'].append(9.35)  # 实时价格
            stockDataTemp['vol'].append(330744)
            stockDataTemp['amount'].append(305686596)
            cacheValue.Cache[stockCode]['count'] = cacheValue.Cache[stockCode]['count'] + 1
            print('数据长度' + str(cacheValue.Cache[stockCode]['count']))
            print('实时数据更新成功开始选股...')
    except Exception as e:
        print('实时数据更新失败...')
        print(e)


def uptestreal():
    try:
        redisObkect = getRedis()
        nameset = redisObkect.hgetall('Real_time_Stock_Data')
        keys = nameset.keys()
        for stockCode in cacheValue.STOCK_LIST:
            stockDataTemp = cacheValue.Cache[stockCode]
            cacheSize = len(stockDataTemp['date'])
            stockDataRealTime = stockDataTemp['date'][cacheSize - 1]
            today_time = time.strftime('%Y%m%d ', time.localtime(time.time()))  # 当日时间
            if (nameset[stockCode] is not None):
                jsonResult = json.loads(nameset[stockCode])  # 实时数据json格式
                # 判断是否有今天的数据 有就更新 没有就添加数据
                if (stockDataRealTime == int(today_time)):
                    stockDataTemp['yclose'][cacheSize - 1] = jsonResult['preClose']
                    stockDataTemp['open'][cacheSize - 1] = (jsonResult['open'])  # 开盘
                    stockDataTemp['high'][cacheSize - 1] = (jsonResult['high'])
                    stockDataTemp['low'][cacheSize - 1] = (jsonResult['low'])
                    stockDataTemp['close'][cacheSize - 1] = (jsonResult['newPrice'])  # 实时价格
                    stockDataTemp['vol'][cacheSize - 1] = (jsonResult['vol'])
                    stockDataTemp['amount'][cacheSize - 1] = (jsonResult['money'])
                else:
                    stockDataTemp['date'].append(int(jsonResult['dateTime'][0:8]))  # 时间
                    stockDataTemp['yclose'].append(jsonResult['preClose'])  # 昨收
                    stockDataTemp['open'].append(jsonResult['open'])  # 开盘
                    stockDataTemp['high'].append(jsonResult['high'])
                    stockDataTemp['low'].append(jsonResult['low'])
                    stockDataTemp['close'].append(jsonResult['newPrice'])  # 实时价格
                    stockDataTemp['vol'].append(jsonResult['vol'])
                    stockDataTemp['amount'].append(jsonResult['money'])
                    cacheValue.Cache[stockCode]['count'] = cacheValue.Cache[stockCode]['count'] + 1
            # else:
            #     print(stockCode+'实时行情数据异常')
        print('实时数据更新成功开始选股...')
    except Exception as e:
        print('实时数据更新失败...')
        print(e)


# 岛型反转
def dxfz():
    runConfig = {
        # 系统指标名字
        # "Name":"MA",
        # 执行的脚本
        "Script": '''
            T:=BARSLAST(H<REF(L,1));
            T2:=T+1;
            TJ:=HHV(H,T2);
            TJ1:TJ<REF(L,T2);
            XG:REF(TJ1,1) AND L>REF(HHV(H,T2),1);
                ''',

        # 脚本参数
        # "Args":[ { "Name": 'N1', "Value": 5 },{ "Name": 'N2', "Value": 10 },{ "Name": 'N3', "Value": 15 } ],
        "Args": [{"Name": "M1", "Value": 15}, {"Name": "M2", "Value": 20}, {"Name": "M3", "Value": 30}],
        # 周期 复权
        "Period": 0, "Right": 0,
        # 股票池
        "Symbol": [],
        # 并行计算加速模式
        "Mode": {"Thread": False, "MinRunCount": 1000, "Count": 5},
        # 输出数据个数 如果只需要最后几个数据可以填几个的个数, 数据从最后开始返回的, 如1=返回最后1个数据 2=返回最后2个数组,  -1=返回所有的数据
        "OutCount": 1,
        # 单个股票执行完是否立即清空缓存, 更具K线个数配置, 不清空缓存到占用很多内存
        "ClearCache": True

        # 获利盘:MA(WINNER(CLOSE),3) * 100 ;
    }

    # 加载股票列表到配置中
    for i in cacheValue.STOCK_LIST:
        runConfig["Symbol"].append(i)

    sourceUrl = 'data\mfinancial_data\mfinancial.csv';
    Cap_Df = pd.read_csv(sourceUrl)
    mDict = Cap_Df.set_index('ths_thscode_stock').T.to_dict('list')
    cacheValue.CAPITAL_LIST.append(mDict)

    jsConfig = json.dumps(runConfig)  # 运行配置项
    hqData = HQChartData()  # 实例化数据类
    result = HQResultTest()  # 实例计算结果接收类
    result.IsOutLog = False

    start = time.process_time()
    res = FastHQChart.Run(jsConfig, hqData, proSuccess=result.RunSuccess, procFailed=result.RunFailed)
    elapsed = (time.process_time() - start)
    log = "岛型反转 Time used:{0}, 股票个数:{1}".format(elapsed, len(runConfig['Symbol']))
    print(log)

    # 选股结果存入mysql
    con = pymysql.connect('192.168.0.152', 'root', 'root')
    cur = con.cursor()
    cur.execute('use cg152')
    now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    for stockResult in result.Result:
        print(stockResult['Symbol'])
        cur.execute("insert into fnc_warning values('%s','%s','%s','%s','%s')" % (
            stockResult['Symbol'], stockResult['StockName'], '岛型反转', 3, now_time))
    cur.execute('select * from fnc_warning')
    a = cur.fetchall()
    con.commit()
    con.close()


def zczx():  # 早晨之星
    runConfig = {
        # 系统指标名字
        # "Name":"MA",
        # 执行的脚本
        "Script": '''
            XG:REF(CLOSE,2)/REF(OPEN,2)<0.95&&
            REF(OPEN,1)<REF(CLOSE,2)&&
            ABS(REF(OPEN,1)-REF(CLOSE,1))/REF(CLOSE,1)<0.03&&
            CLOSE/OPEN>1.05&&CLOSE>REF(CLOSE,2);
                        ''',

        # 脚本参数
        # "Args":[ { "Name": 'N1', "Value": 5 },{ "Name": 'N2', "Value": 10 },{ "Name": 'N3', "Value": 15 } ],
        "Args": [{"Name": "M1", "Value": 15}, {"Name": "M2", "Value": 20}, {"Name": "M3", "Value": 30}],
        # 周期 复权
        "Period": 0, "Right": 0,
        # 股票池
        "Symbol": [],
        # 并行计算加速模式
        "Mode": {"Thread": False, "MinRunCount": 1000, "Count": 5},
        # 输出数据个数 如果只需要最后几个数据可以填几个的个数, 数据从最后开始返回的, 如1=返回最后1个数据 2=返回最后2个数组,  -1=返回所有的数据
        "OutCount": 1,
        # 单个股票执行完是否立即清空缓存, 更具K线个数配置, 不清空缓存到占用很多内存
        "ClearCache": True,

        "JobID": "5"

        # 获利盘:MA(WINNER(CLOSE),3) * 100 ;
    }

    # 加载股票列表到配置中
    for i in cacheValue.STOCK_LIST:
        runConfig["Symbol"].append(i)

    sourceUrl = 'data\mfinancial_data\mfinancial.csv';
    Cap_Df = pd.read_csv(sourceUrl)
    mDict = Cap_Df.set_index('ths_thscode_stock').T.to_dict('list')
    cacheValue.CAPITAL_LIST.append(mDict)

    jsConfig = json.dumps(runConfig)  # 运行配置项
    hqData = HQChartData()  # 实例化数据类
    result = HQResultTest()  # 实例计算结果接收类
    result.IsOutLog = False

    start = time.process_time()
    res = FastHQChart.Run(jsConfig, hqData, proSuccess=result.RunSuccess, procFailed=result.RunFailed)
    elapsed = (time.process_time() - start)
    log = "早晨之星 Time used:{0}, 股票个数:{1}".format(elapsed, len(runConfig['Symbol']))
    print(log)
    warringResultToRedis(5, result.Result)
    # r = redis.StrictRedis(host='192.168.0.164', port=6379, db=0, password='')
    # r.hset("FNC_WARRING", "zczx", result.Result)  # 将内容写入redis


def cxyx():  # 长下影线
    runConfig = {
        # 系统指标名字
        # "Name":"MA",
        # 执行的脚本
        "Script": '''
                TJ1:=MIN(CLOSE,OPEN)-LOW;
                TJ2:=HIGH-LOW;
                TJ3:=TJ1 / TJ2;
                XG:TJ3 > 0.85;
                    ''',

        # 脚本参数
        # "Args":[ { "Name": 'N1', "Value": 5 },{ "Name": 'N2', "Value": 10 },{ "Name": 'N3', "Value": 15 } ],
        "Args": [{"Name": "M1", "Value": 15}, {"Name": "M2", "Value": 20}, {"Name": "M3", "Value": 30}],
        # 周期 复权
        "Period": 0, "Right": 0,
        # 股票池
        "Symbol": [],
        # 并行计算加速模式
        "Mode": {"Thread": False, "MinRunCount": 1000, "Count": 5},
        # 输出数据个数 如果只需要最后几个数据可以填几个的个数, 数据从最后开始返回的, 如1=返回最后1个数据 2=返回最后2个数组,  -1=返回所有的数据
        "OutCount": 1,
        # 单个股票执行完是否立即清空缓存, 更具K线个数配置, 不清空缓存到占用很多内存
        "ClearCache": True,

        "JobID": "3"

        # 获利盘:MA(WINNER(CLOSE),3) * 100 ;
    }

    # 加载股票列表到配置中
    for i in cacheValue.STOCK_LIST:
        runConfig["Symbol"].append(i)

    sourceUrl = 'data\mfinancial_data\mfinancial.csv';
    Cap_Df = pd.read_csv(sourceUrl)
    mDict = Cap_Df.set_index('ths_thscode_stock').T.to_dict('list')
    cacheValue.CAPITAL_LIST.append(mDict)

    jsConfig = json.dumps(runConfig)  # 运行配置项
    hqData = HQChartData()  # 实例化数据类
    result = HQResultTest()  # 实例计算结果接收类
    result.IsOutLog = False

    start = time.process_time()
    res = FastHQChart.Run(jsConfig, hqData, proSuccess=result.RunSuccess, procFailed=result.RunFailed)
    elapsed = (time.process_time() - start)
    log = "长下影线 Time used:{0}, 股票个数:{1}".format(elapsed, len(runConfig['Symbol']))
    print(log)
    # r = getRedis()
    # r.hset("FNC_WARRING","cxyx", result.Result)  # 将内容写入redis
    # 选股结果存入mysql

    warringResultToRedis(3, result.Result)
    # con = pymysql.connect('192.168.0.152', 'root', 'root')
    # cur = con.cursor()
    # cur.execute('use cg152')
    # now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    # for stockResult in result.Result:
    #     print(stockResult['Symbol'])
    #     cur.execute("insert into fnc_warning values('%s','%s','%s','%s','%s')" % (
    #         stockResult['Symbol'], stockResult['StockName'], '长下影线', 4, now_time))
    # cur.execute('select * from fnc_warning')
    # a = cur.fetchall()
    # con.commit()
    # con.close()


def dfp():  # 多方炮
    runConfig = {
        # 系统指标名字
        # "Name":"MA",
        # 执行的脚本
        "Script": '''
                A1:=REF(C,2)>REF(O,2)*1.03;
                A2:=REF(C,1)<REF(O,1)*1.005 AND REF(C,1)<REF(C,2);
                A3:=C>O*1.023 AND C>REF(C,1)*0.99;
                XG:A1 AND A2 AND A3;
                    ''',

        # 脚本参数
        # "Args":[ { "Name": 'N1', "Value": 5 },{ "Name": 'N2', "Value": 10 },{ "Name": 'N3', "Value": 15 } ],
        "Args": [{"Name": "M1", "Value": 15}, {"Name": "M2", "Value": 20}, {"Name": "M3", "Value": 30}],
        # 周期 复权
        "Period": 0, "Right": 0,
        # 股票池
        "Symbol": [],
        # 并行计算加速模式
        "Mode": {"Thread": False, "MinRunCount": 1000, "Count": 5},
        # 输出数据个数 如果只需要最后几个数据可以填几个的个数, 数据从最后开始返回的, 如1=返回最后1个数据 2=返回最后2个数组,  -1=返回所有的数据
        "OutCount": 1,
        # 单个股票执行完是否立即清空缓存, 更具K线个数配置, 不清空缓存到占用很多内存
        "ClearCache": True,

        "JobID": "6"

        # 获利盘:MA(WINNER(CLOSE),3) * 100 ;
    }

    # 加载股票列表到配置中
    for i in cacheValue.STOCK_LIST:
        runConfig["Symbol"].append(i)

    sourceUrl = 'data\mfinancial_data\mfinancial.csv';
    Cap_Df = pd.read_csv(sourceUrl)
    mDict = Cap_Df.set_index('ths_thscode_stock').T.to_dict('list')
    cacheValue.CAPITAL_LIST.append(mDict)

    jsConfig = json.dumps(runConfig)  # 运行配置项
    hqData = HQChartData()  # 实例化数据类
    result = HQResultTest()  # 实例计算结果接收类
    result.IsOutLog = False

    start = time.process_time()
    res = FastHQChart.Run(jsConfig, hqData, proSuccess=result.RunSuccess, procFailed=result.RunFailed)
    elapsed = (time.process_time() - start)
    log = "多方炮 Time used:{0}, 股票个数:{1}".format(elapsed, len(runConfig['Symbol']))
    print(log)
    # r = getRedis()
    # r.hset("FNC_WARRING","cxyx", result.Result)  # 将内容写入redis
    # 选股结果存入mysql

    warringResultToRedis(6, result.Result)
    # con = pymysql.connect('192.168.0.152', 'root', 'root')
    # cur = con.cursor()
    # cur.execute('use cg152')
    # now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    # for stockResult in result.Result:
    #     print(stockResult['Symbol'])
    #     cur.execute("insert into fnc_warning values('%s','%s','%s','%s','%s')" % (
    #         stockResult['Symbol'], stockResult['StockName'], '长下影线', 4, now_time))
    # cur.execute('select * from fnc_warning')
    # a = cur.fetchall()
    # con.commit()
    # con.close()


# 指标选股
def ZBXG():
    # 更新当日选股的实时数据
    UPdateRealTimeData()
    # TestUp()
    yycdx()  # 一阳穿多线
    sdgz_dx()  # 四点共振
    # dxfz()#岛型反转
    cxyx()  # 长下影线
    sdgz_zx()  # 四点共振中线选股
    zczx()  # 早晨之星形态选股
    dfp()  # 多方炮形态选股
# 指标选股
def ZBXGTest():
    # 更新当日选股的实时数据
    UPdateRealTimeData()
    F_L_S_G.fuc_run()#放量上攻
    D_T_P_L.fuc_run()#多头排列
    D_K_D_Y_X.fuc_run()#低开大阳线
    J_S_J.fuc_run()#金三角
    D_X_F_Z.fuc_run()#岛形反转
    Q_S_Z_L.fuc_run()#强势整理
    X_R_Z_L.fuc_run()#仙人指路

    # yycdx()  # 一阳穿多线
    # sdgz_dx()  # 四点共振
    # # dxfz()#岛型反转
    # cxyx()  # 长下影线
    # sdgz_zx()  # 四点共振中线选股
    # zczx()  # 早晨之星形态选股
    # dfp()  # 多方炮形态选股



def sendWarningMessage(stockCode):
    print('选股引擎----' + str(stockCode) + "实时行情报警------------------------------------------------------------")
    pass

def cacheFin():
    #缓存财务数据
    sourceUrl = 'data\mfinancial_data\mfinancial.csv';
    Cap_Df = pd.read_csv(sourceUrl)
    mDict = Cap_Df.set_index('ths_thscode_stock').T.to_dict('list')
    cacheValue.CAPITAL_LIST.append(mDict)
    pass
if __name__ == "__main__":
    # 选股指标type  1:
    # 本机
    key="ZNl/N0X3z04ZP9jDFgG6gfmij2tWDDaaUxRdrPdYMqXOJqQ2aZTR6pnzG68g54XDRTg3Gx4kadrom8zJMHoGddxMfCG+3KjL13XpYIP/TPFMqIbTXh5e8zMqzQzNDpHoW5dKX6wIXYwKCqNhh01eBD3I2X9otxp3jxhM2ZW+cwNqotJtG4A8sjJNl/N+Rhxp0rR5r8a1LSSPURfh0on11XVRW9D/gH1yihjxriOCIfRBVuIfKjmNl9Q4YsnBqExc14+IZI5H+cMOo40e6j3ebsPewdmuO7JOPUHJZ37UGMTNeXqo3Q0WKsYkRJPZpNQmzgDOTl2DAwPgX9kuDe5Ghg=="
    # 158 old
    #key = "DAJFxZuqjh0oVAMWy/5YWHczOEBBE2GA8TR6kez1sClV0FZzb10zdbPhASqnWWjGkb9se775jTv0W3DiF7nqJ+cRuhL3NmDXlrVUTOf2MlnOcxInU10ffwklnGAoe4tWJDJ4Slumioenvo9IGdkNTdof/LCLnO/aCRMtO4WWwGk+3bO4Y2jq1KoFXAItytYlPTez+WttIWo0SCGTV0/oYGarEOjbEcO2IXvxdF7Xc8SV5vB7WVAH9ebAZ883P2WOYS5mWH6p+OMbSKBb5ZNvr16as9zkY0fV3GEGD94cF8sFmba7CtCONiDXYUWHBjLqFh2V8DJhcgFehrKySFO5Qw=="
    # 158 new
    #key = "yQJq2kpL5tLTHMY6nA86zl1IuM9AIcIOy3Ac2S1jigGWE55E7exTtusaoGhSNZjqbBndYRM6F0GEDz5py+9zW21uKKBw9W2y6hnOyDezhbWor6j8b/kBK5lC7C9YUZkYCkZC04adLH93pVvvBv3TMlQo/nKGPuB99xxr47KixIBZRzd+WySVkfrJ4vEweTMdjonHI2ouqvSWRKqfc9OdffnphUvv7zSKOyeVcAssk9TJXFHNMx7RMti75rv8SzrImQ2+HiNBeBpfXg6qW+N6645LpLK5bsOOSYu+GIzTmVvtgVlq6oifY76q8GrDZNyjrgX9Zw6ysWgy4mZ6pyfWlg=="
    FastHQChart.Initialization(key)
    # jsSystemIndex = json.dumps(FastHQChart.HQCHART_SYSTEM_INDEX)
    # FastHQChart.AddSystemIndex(jsSystemIndex)

    # 初始化定时器设置
    # scheduler = BlockingScheduler()
    scheduler = BlockingScheduler(timezone='Asia/Shanghai')
    today_time = time.strftime('%Y-%m-%d ', time.localtime(time.time()))

    print('1:启动选股引擎 2:同步股票列表 3:同步财务数据 4:同步历史数据文件 5:退出程序 6:测试选股 7:多线程缓存')

    mOperation = ''
    while mOperation != '5':
        mResult = input()
        if (mResult == '1'):
            readStockList()  # 读取股票列表
            LoadHisLineMemory()
            # trigger_interval = IntervalTrigger(seconds=160)
            # scheduler.add_job(ZBXGTest, trigger_interval,  start_date=today_time + '09:31:00',
            #                   end_date=today_time + '11:30:00')
            # scheduler.add_job(ZBXGTest, trigger_interval,  start_date=today_time + '13:01:00',
            #                   end_date=today_time + '15:00:00')
            # # 每天自动缓存当天历史数据
            # scheduler.add_job(readSingleStockKlineHistory, "cron", day_of_week="0-4", hour="15", minute="10")
            # scheduler.start()
            trigger_interval_ONE = IntervalTrigger(seconds=120,start_date=today_time + '09:31:00',
                              end_date=today_time + '11:30:00')
            trigger_interval_TWO = IntervalTrigger(seconds=120,start_date=today_time + '13:01:00',
                              end_date=today_time + '15:00:00')
            scheduler.add_job(ZBXGTest, trigger_interval_ONE)
            scheduler.add_job(ZBXGTest, trigger_interval_TWO)

            cron_trigger = CronTrigger(day_of_week="0-4", hour="15", minute="10")
            # 每天自动缓存当天历史数据
            scheduler.add_job(readSingleStockKlineHistory,cron_trigger)
            scheduler.start()
        if (mResult == '2'):
            cacheStoctList()  # 缓存股票列表
        if (mResult == '3'):
            # 同步财务数据文件并且在程序里面缓存
            synFinance()
        if (mResult == '4'):
            readSingleStockKlineHistory()  # 读取所有历史记录
        if (mResult == '5'):
            print('关闭程序')
        if (mResult == '6'):
            readStockList()  # 读取股票列表
            cacheFin()#缓存财务数据
            LoadHisLineMemory()
            UPdateRealTimeData()
            # ZBXG()
            ZBXGTest()
        if (mResult == '7'):
            ZBXGTest()


    # readStockList() #读取股票列表

    # TestMultiStock()
